<template>
  <div class="applications-page">
    <!-- 顶部导航栏 -->
    <header class="page-header">
      <div class="header-container">
        <div class="logo-section">
          <div class="logo-icon">
            <img :src="logoImage" alt="Logo" class="logo-image" />
          </div>
          <h1 class="logo-title" @click="goToHome">云启国际人才港</h1>
        </div>
        <nav class="navigation">
          <a href="#" class="nav-link active">申请列表</a>
          <a href="#" class="nav-link" @click="goToHome">首页</a>
          <a href="#" class="nav-link" @click="goToTalentSearch">人才库</a>
        </nav>
        <div class="right-section">
          <a href="#" class="nav-link" @click="goToEnterpriseSpace">企业空间</a>
          <div class="nav-icons">
            <div class="icon-item">
              <el-icon size="18"><Bell /></el-icon>
            </div>
            <div class="icon-item">
              <el-icon size="18"><User /></el-icon>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- 申请列表主内容 -->
    <div class="applications-main">
      <!-- 页面标题和统计 -->
      <section class="page-header-section">
        <div class="container">
          <div class="header-content">
            <div class="title-section">
              <h1 class="page-title">申请管理</h1>
              <p class="page-subtitle">高效管理收到的申请，快速筛选合适人才</p>
            </div>
            <div class="stats-section">
              <div class="stat-card">
                <div class="stat-icon">
                  <el-icon size="24"><Document /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.totalApplications }}</div>
                  <div class="stat-label">总申请数</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon pending">
                  <el-icon size="24"><Clock /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.pendingApplications }}</div>
                  <div class="stat-label">待处理</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon approved">
                  <el-icon size="24"><Check /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.approvedApplications }}</div>
                  <div class="stat-label">已通过</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon rejected">
                  <el-icon size="24"><Close /></el-icon>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.rejectedApplications }}</div>
                  <div class="stat-label">已拒绝</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 筛选和操作区域 -->
      <section class="filter-section">
        <div class="container">
          <div class="filter-container">
            <div class="filter-left">
              <el-input
                v-model="searchQuery"
                placeholder="搜索申请人姓名或需求标题"
                class="search-input"
                size="large"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              
              <el-select v-model="statusFilter" placeholder="申请状态" class="filter-select">
                <el-option label="全部状态" value="" />
                <el-option label="已提交" value="submitted" />
                <el-option label="平台处理中" value="platform_processing" />
                <el-option label="对接成功" value="successful_match" />
                <el-option label="对接失败" value="failed_match" />
              </el-select>
            </div>
            
            <div class="filter-right">
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="resetFilters" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
              <el-button type="success" @click="exportApplications" class="export-btn">
                <el-icon><Download /></el-icon>
                导出
              </el-button>
            </div>
          </div>
        </div>
      </section>

      <!-- 申请列表 -->
      <section class="applications-list-section">
        <div class="container">
          <div class="list-header">
            <h2 class="list-title">申请列表</h2>
            <div class="list-actions">
              <el-button type="primary" @click="batchApprove" :disabled="!hasSelected">
                批量通过
              </el-button>
              <el-button type="danger" @click="batchReject" :disabled="!hasSelected">
                批量拒绝
              </el-button>
            </div>
          </div>
          
          <div class="applications-table">
            <el-table
              :data="applications"
              @selection-change="handleSelectionChange"
              style="width: 100%"
              class="applications-table"
              v-loading="loading"
              element-loading-text="加载中..."
              element-loading-spinner="el-icon-loading"
            >
              <el-table-column type="selection" width="55" />
              
              <el-table-column label="学生信息" width="200">
                <template #default="scope">
                  <div class="applicant-info">
                    <el-avatar :size="40" icon="User" />
                    <div class="applicant-details">
                      <div class="applicant-name">{{ scope.row.studentMaskedName }}</div>
                      <div class="applicant-nationality">留学生</div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column label="申请时间" width="180">
                <template #default="scope">
                  <div class="application-time">
                    {{ formatDate(scope.row.requestTime) }}
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column label="状态" width="150">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.requestStatus)">
                    {{ scope.row.statusDisplay }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column label="状态描述" width="300">
                <template #default="scope">
                  <div class="status-description">
                    {{ scope.row.statusDescription }}
                  </div>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <div class="action-buttons">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="viewApplication(scope.row)"
                    >
                      查看
                    </el-button>
                                         <el-button 
                       type="success" 
                       size="small" 
                       @click="approveApplication(scope.row)"
                       v-if="scope.row.requestStatus === 'submitted'"
                     >
                       通过
                     </el-button>
                     <el-button 
                       type="danger" 
                       size="small" 
                       @click="rejectApplication(scope.row)"
                       v-if="scope.row.requestStatus === 'submitted'"
                     >
                       拒绝
                     </el-button>
                    <el-button 
                      type="info" 
                      size="small" 
                      @click="contactApplicant(scope.row)"
                    >
                      沟通
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </section>
    </div>

    <!-- 申请详情对话框 -->
    <el-dialog 
      v-model="showDetailDialog" 
      title="申请详情" 
      width="800px"
      :before-close="handleCloseDetailDialog"
    >
      <div v-if="selectedApplication" class="application-detail">
                 <div class="detail-section">
           <h3>学生信息</h3>
           <div class="detail-content">
             <div class="detail-item">
               <span class="label">学生姓名：</span>
               <span class="value">{{ selectedApplication.studentMaskedName }}</span>
             </div>
             <div class="detail-item">
               <span class="label">请求ID：</span>
               <span class="value">{{ selectedApplication.requestId }}</span>
             </div>
             <div class="detail-item">
               <span class="label">申请时间：</span>
               <span class="value">{{ formatDate(selectedApplication.requestTime) }}</span>
             </div>
           </div>
         </div>
         
         <div class="detail-section">
           <h3>申请状态</h3>
           <div class="detail-content">
             <div class="detail-item">
               <span class="label">当前状态：</span>
               <el-tag :type="getStatusType(selectedApplication.requestStatus)">
                 {{ selectedApplication.statusDisplay }}
               </el-tag>
             </div>
             <div class="detail-item">
               <span class="label">状态描述：</span>
               <span class="value">{{ selectedApplication.statusDescription }}</span>
             </div>
           </div>
         </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
                     <el-button 
             type="success" 
             @click="approveApplication(selectedApplication)"
             v-if="selectedApplication?.requestStatus === 'submitted'"
           >
             通过申请
           </el-button>
           <el-button 
             type="danger" 
             @click="rejectApplication(selectedApplication)"
             v-if="selectedApplication?.requestStatus === 'submitted'"
           >
             拒绝申请
           </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  User, Bell, Document, Clock, Check, Close, Search, 
  Refresh, Download, Edit, Message 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import logoImage from '../../assets/images/login/logo2.png'
import { applicationApi } from '@/api'

const router = useRouter()

// 统计数据
const stats = ref({
  totalApplications: 0,
  pendingApplications: 0,
  approvedApplications: 0,
  rejectedApplications: 0
})

// 筛选条件
const searchQuery = ref('')
const statusFilter = ref('')

// 申请列表数据
const applications = ref([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)

// 企业信息
const enterpriseInfo = ref({
  enterpriseId: null,
  enterpriseName: ''
})

// 选中的申请
const selectedApplications = ref([])

// 详情对话框
const showDetailDialog = ref(false)
const selectedApplication = ref(null)

// 计算属性
const hasSelected = computed(() => selectedApplications.value.length > 0)

// 导航方法
const goToHome = () => {
  router.push({ name: 'enterprise-home' })
}

const goToTalentSearch = () => {
  router.push({ name: 'talent-search' })
}



const goToEnterpriseSpace = () => {
  router.push({ name: 'enterprise-space' })
}

// 加载申请列表数据
const loadApplications = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 添加状态筛选
    if (statusFilter.value) {
      params.status = statusFilter.value
    }
    
    const response = await applicationApi.getMyRequests(params)
    
    if (response.code === 200) {
      applications.value = response.data.requests || []
      total.value = response.data.pagination?.totalCount || 0
      enterpriseInfo.value = response.data.enterpriseInfo || {}
      
      // 更新统计数据
      updateStats()
      

    } else {
      console.error('获取申请列表失败:', response.message)
      ElMessage.error(response.message || '获取申请列表失败')
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
    ElMessage.error('获取申请列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 更新统计数据
const updateStats = () => {
  const statusCounts = {
    submitted: 0,
    platform_processing: 0,
    successful_match: 0,
    failed_match: 0
  }
  
  applications.value.forEach(app => {
    if (statusCounts.hasOwnProperty(app.requestStatus)) {
      statusCounts[app.requestStatus]++
    }
  })
  
  stats.value = {
    totalApplications: total.value,
    pendingApplications: statusCounts.submitted + statusCounts.platform_processing,
    approvedApplications: statusCounts.successful_match,
    rejectedApplications: statusCounts.failed_match
  }
}

// 搜索和筛选方法
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  loadApplications()
}

const resetFilters = () => {
  searchQuery.value = ''
  statusFilter.value = ''
  currentPage.value = 1
  loadApplications()
  ElMessage.info('筛选条件已重置')
}

const exportApplications = () => {
  ElMessage.success('申请数据导出功能正在开发中')
}

// 表格操作方法
const handleSelectionChange = (selection) => {
  selectedApplications.value = selection
}

const viewApplication = (application) => {
  selectedApplication.value = application
  showDetailDialog.value = true
}

const approveApplication = async (application) => {
  ElMessage.info('撮合申请状态由平台管理，企业无法直接修改状态')
}

const rejectApplication = async (application) => {
  ElMessage.info('撮合申请状态由平台管理，企业无法直接修改状态')
}

const contactApplicant = (application) => {
  if (application.requestStatus === 'successful_match') {
    ElMessage.success('对接成功！平台已提供双方联系方式，请及时与学生沟通')
  } else {
    ElMessage.info('请等待平台处理完成后再进行沟通')
  }
}

const batchApprove = async () => {
  ElMessage.info('撮合申请状态由平台管理，企业无法直接修改状态')
}

const batchReject = async () => {
  ElMessage.info('撮合申请状态由平台管理，企业无法直接修改状态')
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  loadApplications()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadApplications()
}

// 工具方法
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const getStatusType = (status) => {
  switch (status) {
    case 'submitted': return 'warning'
    case 'platform_processing': return 'primary'
    case 'successful_match': return 'success'
    case 'failed_match': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'submitted': return '已提交'
    case 'platform_processing': return '平台处理中'
    case 'successful_match': return '对接成功'
    case 'failed_match': return '对接失败'
    default: return '未知'
  }
}

const getMatchColor = (rate) => {
  if (rate >= 90) return '#67C23A'
  if (rate >= 80) return '#E6A23C'
  if (rate >= 70) return '#F56C6C'
  return '#909399'
}

const handleCloseDetailDialog = () => {
  showDetailDialog.value = false
  selectedApplication.value = null
}

// 组件挂载
onMounted(() => {
  
  loadApplications()
})
</script>

<style scoped>
.applications-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
}

/* 顶部导航栏 */
.page-header {
  background: #6c757d;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 16px 0;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  position: relative;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
}

.logo-icon {
  display: flex;
  align-items: center;
}

.logo-image {
  width: 32px;
  height: 32px;
  object-fit: contain;
  filter: none;
}

.logo-title {
  font-size: 1.4rem;
  font-weight: 600;
  color: white;
  margin: 0;
}

.navigation {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 40px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-link {
  color: white;
  text-decoration: none;
  font-weight: 500;
  font-size: 15px;
  transition: color 0.2s ease;
  position: relative;
  padding: 8px 0;
}

.nav-link:hover {
  color: #e9ecef;
}

.nav-link.active {
  color: #ffffff;
  font-weight: 600;
}

.nav-link.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: #ffffff;
}

.nav-icons {
  display: flex;
  align-items: center;
  gap: 16px;
}

.icon-item {
  color: white;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.icon-item:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

/* 主内容区域 */
.applications-main {
  padding: 40px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面标题和统计区域 */
.page-header-section {
  margin-bottom: 40px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.title-section {
  flex: 1;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  min-width: 140px;
}

.stat-icon {
  color: #ffd700;
  font-size: 1.5rem;
}

.stat-icon.pending {
  color: #ffa500;
}

.stat-icon.approved {
  color: #52c41a;
}

.stat-icon.rejected {
  color: #ff4d4f;
}

.stat-content {
  text-align: center;
}

.stat-number {
  font-size: 1.8rem;
  font-weight: 700;
  color: white;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.8);
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 30px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 25px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.filter-left {
  display: flex;
  gap: 15px;
  flex: 1;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.filter-right {
  display: flex;
  gap: 10px;
}

.search-btn, .reset-btn, .export-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 申请列表区域 */
.applications-list-section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 30px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.list-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: white;
  margin: 0;
}

.list-actions {
  display: flex;
  gap: 10px;
}

/* 表格样式 */
.applications-table {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  overflow: hidden;
}

.applicant-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.applicant-details {
  display: flex;
  flex-direction: column;
}

.applicant-name {
  font-weight: 600;
  color: #333;
}

.applicant-nationality {
  font-size: 0.9rem;
  color: #666;
}

.demand-info {
  display: flex;
  flex-direction: column;
}

.demand-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.demand-type {
  font-size: 0.9rem;
  color: #666;
}

.application-time {
  color: #666;
  font-size: 0.9rem;
}

.match-rate {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.match-text {
  font-size: 0.9rem;
  color: #666;
}

.status-description {
  font-size: 0.9rem;
  color: #666;
  line-height: 1.4;
}

.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

/* 分页容器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* 申请详情对话框 */
.application-detail {
  color: #333;
}

.detail-section {
  margin-bottom: 25px;
}

.detail-section h3 {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e8e8e8;
}

.detail-content {
  padding-left: 10px;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
}

.label {
  font-weight: 600;
  color: #666;
  min-width: 80px;
}

.value {
  color: #333;
  flex: 1;
}

.application-reason {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  line-height: 1.6;
  color: #333;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 30px;
  text-align: center;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .stats-section {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .filter-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .filter-left {
    flex-direction: column;
    width: 100%;
  }
  
  .search-input, .filter-select {
    width: 100%;
  }
  
  .list-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style> 